import { eventHandler, getMethod, createError } from "h3";

// 模拟商品数据存储 (实际项目中这应该是共享的数据层)
const products = [
  {
    id: 1,
    name: "iPhone 15",
    price: 7999,
    description: "最新款苹果手机",
    category: "电子产品",
    stock: 50,
    createTime: new Date("2024-01-01").toISOString(),
  },
  {
    id: 2,
    name: "MacBook Pro",
    price: 15999,
    description: "高性能笔记本电脑",
    category: "电子产品",
    stock: 30,
    createTime: new Date("2024-01-02").toISOString(),
  },
  {
    id: 3,
    name: "Nike运动鞋",
    price: 899,
    description: "舒适透气运动鞋",
    category: "服饰",
    stock: 100,
    createTime: new Date("2024-01-03").toISOString(),
  },
];

export default eventHandler(async (event) => {
  const method = getMethod(event);

  // GET /api/categories - 获取所有商品分类
  if (method === "GET") {
    // 从商品中提取所有唯一的分类
    const categories = [...new Set(products.map((p) => p.category))];

    // 统计每个分类下的商品数量
    const categoriesWithCount = categories.map((category) => {
      const count = products.filter((p) => p.category === category).length;
      return {
        name: category,
        count: count,
      };
    });

    return {
      success: true,
      data: categoriesWithCount,
      total: categories.length,
    };
  }

  // 不支持的HTTP方法
  throw createError({
    statusCode: 405,
    statusMessage: "Method Not Allowed",
  });
});
